/*
 * Copyright (C) 2015-2021 Alibaba Group Holding Limited
 */

#include <stdio.h>
#include <stdlib.h>
#include <ulog/ulog.h>
#include <cx_debug.h>
#include <time.h>
#include <dirent.h>
#include "cx_hal.h"
#include "cx_utility.h"

#define TAG "cxutility"


/* in unit kb */
int cx_util_get_folder_size(char *path)
{
    DIR *dir;
    struct dirent *out_dirent;
    char file_path[256];
    struct stat file_stat;
    int ret;
    int size = 0;

    dir = opendir(path);
    CHECK_RET_WITH_RET(dir, -1);

    while (1) {
        out_dirent = readdir(dir);
        if(!out_dirent){
            break;
        }

        memset(file_path, 0, 256);
        snprintf(file_path, 256, "%s/%s", path, out_dirent->d_name);
        ret = stat(file_path, &file_stat);
        if (ret == 0) {
            size += file_stat.st_size / 1024;
        }
	}

    closedir(dir);

    return size;
}

int cx_util_force_rmdir(char *path)
{
    DIR *dir;
    struct dirent *out_dirent;
    char file_path[256];
    int size = 0;

    dir = opendir(path);
    CHECK_RET_WITH_RET(dir, -1);

    while (1) {
        out_dirent = readdir(dir);
        if(!out_dirent){
            break;
        }

        memset(file_path, 0, 256);
        snprintf(file_path, 256, "%s/%s", path, out_dirent->d_name);
        unlink(file_path);

        // LOGD(TAG, "rm file %s", file_path);
	}

    closedir(dir);
    rmdir(path);

    LOGD(TAG, "removed folder %s", path);

    return size;
}

